package marco.android.CouchControl;

import marco.android.CouchControl.TouchPadPanel.TouchPadPanelListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class CanvasSurface extends SurfaceView implements SurfaceHolder.Callback
{
	private TouchPadPanel mPanel;
	CanvasThread mCanvasThread;
	private SurfaceHolder mHolder;
	private Context mContext;

	public CanvasSurface(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mHolder = getHolder();
		getHolder().addCallback(this);
		mContext = context;

		setFocusable(true);
		setFocusableInTouchMode(true);
		setWillNotDraw(true);
		
		mPanel = new TouchPadPanel(context, attrs);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
	{
		mCanvasThread.SurfaceChanged(width, height);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder)
	{
		// TODO Auto-generated method stub
		mCanvasThread = new CanvasThread(mContext , mHolder);
		mPanel.SetDrawingListener(mCanvasThread);
		mCanvasThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		System.out.println("Surface Destroyed.");
		if(mCanvasThread != null)
		{
			mCanvasThread.interrupt();
		}
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		if(mCanvasThread != null)
		{
			mCanvasThread.SurfaceChanged(w, h);
		}
	}

	/**
	 * Standard window-focus override. Notice focus lost so we can pause on
	 * focus lost. e.g. user switches to take a call.
	 */
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus)
	{
		if(!hasWindowFocus)
		{
			mCanvasThread.Pause();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		mPanel.onTouchEvent(event);
		return true;
	}

	public void SetEventListener(TouchPadPanelListener listener)
	{
		mPanel.SetListener(listener);
	}
	
	public void Clear()
	{
	}
}
